package com.zhaolixiang.camera01

import android.app.Activity
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Rect
import android.hardware.Camera
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.io.FileOutputStream

class MainActivity : AppCompatActivity() {
    private  var camera:Camera?=null
    private lateinit var cameraSurfaceView:CameraSurfaceView
    private lateinit var activity:Activity
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        activity=this
        initCamera()
        bt_show.setOnClickListener{
            releaseCamera()
            initCamera()
        }
        bt_capture.setOnClickListener{
            //该方法接受三个参数，
            // 第一个参数ShutterCallback响应快门的接口，
            // 第二个参数PictureCallback接收raw格式的图片数据，
            // 第三个参数PictureCallback接收jpeg格式的图片数据。为了保存图片数据，你需要分别实现以上三个接口。
            // 此处我们暂且实现第三个PictureCallback接口回调
            camera!!.takePicture(null,null,pictureCallBack())
        }
    }
    //初始化相机
    fun initCamera(){
        img.visibility= View.GONE
        //获取camera对象实例
        getCamera()
        try {
            if(camera!=null){
                val params=camera!!.parameters
                // 默认为横屏，设置为竖屏
                camera!!.setDisplayOrientation(90);
                //设置是否可以对焦
                CameraUtils().setParameters(camera!!,Camera.Parameters.FOCUS_MODE_AUTO)
                //设置最优预览效果
                val pointPreview=CameraUtils().findBestPreviewSizeValue(camera!!,activity)
                if(pointPreview!=null){
                    params.setPreviewSize(pointPreview.x,pointPreview.y)
                }
                //设置最优拍照效果
                val pointPicture= CameraUtils().findBestPictureSizeValue(camera!!,activity)
                if(pointPicture!=null){
                    params.setPictureSize(pointPicture.x,pointPicture.y)
                }
                /*val pp=camera!!.parameters
                pp.focusMode=Camera.Parameters.FOCUS_MODE_AUTO
                camera!!.parameters=pp*/
                camera!!.parameters=params
                cameraSurfaceView= CameraSurfaceView(this,camera!!)
                frameLayout.removeAllViews()
                frameLayout.addView(cameraSurfaceView)
            }
        }catch (e:Exception){
            Toast.makeText(this,"设置相机异常，请重试",Toast.LENGTH_LONG).show()
            e.printStackTrace()
        }
    }
    private inner class  pictureCallBack:Camera.PictureCallback{
        override fun onPictureTaken(data: ByteArray?, camera: Camera?) {
            try {
                val file= File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/1.jpg")
                if(!file.exists()){
                    file.createNewFile()
                }
                val fileOutputStream=FileOutputStream(file)

                //val newData=CameraUtils().getCutMatrix(camera!!,data!!,Rect(5000,5000,5000,5000))
                //Log.e("返回值",newData.toString())
                //if(newData==null){
                 //   Log.e("返回值","为空")
                //}
                fileOutputStream.write(data)
                fileOutputStream.close()
                img.visibility=View.VISIBLE
                var bitmap=BitmapFactory.decodeFile(file.path)
                //选择90度
                bitmap=CameraUtils().rotateBitmap(bitmap,90f)
                //bitmap= Bitmap.createBitmap(bitmap,0,0,1920,1080)
                img.setImageBitmap(bitmap)
                releaseCamera()
            }catch (e:Exception){
                Toast.makeText(activity,"拍照失败",Toast.LENGTH_LONG).show()
                e.printStackTrace()
            }
        }

    }

    override fun onResume() {
        super.onResume()
        getCamera()
    }

    override fun onPause() {
        super.onPause()
        releaseCamera()
    }
    //获取相机资源
    fun getCamera(){
        if(camera==null){
            try {
                camera= Camera.open()
            }catch (e:Exception){
                Toast.makeText(this,"获取相机异常，请重试",Toast.LENGTH_LONG).show()
                e.printStackTrace()
            }
        }
    }
    //释放相机资源
    fun releaseCamera(){
        if(camera!=null){
            camera!!.release()
            camera=null
        }
    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        //根据点击事件完成曝光和对焦
        if(camera!=null && event!=null) {
            val focusRect = calculateArea(event.getRawX(), event.getRawY(), 1f)
            val meteringRect = calculateArea(event.getRawX(), event.getRawY(), 1.5f)

            val parameters = camera!!.getParameters()
            parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_AUTO)

            if (parameters.getMaxNumFocusAreas() > 0) {
                val focusAreas = ArrayList<Camera.Area>()
                focusAreas.add(Camera.Area(focusRect, 1000))

                parameters.setFocusAreas(focusAreas)
            }

            if (parameters.getMaxNumMeteringAreas() > 0) {
                val meteringAreas = ArrayList<Camera.Area>()
                meteringAreas.add(Camera.Area(meteringRect, 1000))

                parameters.setMeteringAreas(meteringAreas)
            }

            camera!!.setParameters(parameters)
            camera!!.autoFocus(myAutoFocusCallback())
        }
        return super.onTouchEvent(event)
    }
    private inner class  myAutoFocusCallback:Camera.AutoFocusCallback {
        override fun onAutoFocus(success: Boolean, camera: Camera?) {
        }
    }


        private  fun calculateArea(x:Float,y:Float,coefficient:Float):Rect{
        val focusAreaSize=300f
        val areaSize:Int=(focusAreaSize*coefficient).toInt()
        val centerX=x/CameraUtils().getResolution(camera!!).width*2000-1000;
        val centerY=y/CameraUtils().getResolution(camera!!).height*2000-1000;
        val left=clamp((centerX-areaSize/2).toInt(),-1000,1000)
        val right = clamp(left + areaSize, -1000, 1000);
        val top = clamp((centerY - areaSize / 2).toInt(), -1000, 1000);
        val bottom = clamp(top + areaSize, -1000, 1000);

        return  Rect(left, top, right, bottom);
    }

    private fun clamp(x: Int, min: Int, max: Int): Int {
        if (x > max) {
            return max
        }
        return if (x < min) {
            min
        } else x
    }

}
